<?php

require __DIR__.'/vendor/autoload.php';
use DiDom\Document;
// http://www.zhongyoo.com/yaoshan/10394.html


// $url = 'http://www.zhongyoo.com/yaoshan/10394.html';


// $document = new Document($url, true, 'GB2312');

// echo $document->first('head title')->text(); return;

// $posts = $document->find('#contentText');

// print_r($posts);

// // foreach($posts as $post) {
// //     echo $post->text(), "\n";
// // }

// http://www.zhongyoo.com/yaoshan/10395.html
// //id range = 

//.listbox

function fetchMenus($page=1){
    $page1 = 'http://www.zhongyoo.com/yaoshan/page_'.$page.'.html'; //1~22
    $document = new Document($page1, true, 'GB2312');
    $menus = $document->find('.listbox a');
    $lines = [];
    foreach($menus as $mu){
        // echo $mu->text(), ' ', $mu->getAttribute('href'), "\n";
        $lines[] = [$mu->text(), $mu->getAttribute('href')];
    }
    return $lines;
}
// $menus = [];
// for($i=1;$i<23;$i++){
//     $menus = array_merge($menus, fetchMenus($i));
// }
// file_put_contents('menus.json', json_encode($menus, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES));
// print_r($menus);

function fetchContent($url){
    $document = new Document($url, true, 'GB2312');
    $posts = $document->find('#contentText');
    if(empty($posts[0])) return '';
    return $posts[0]->text();
}

// set_time_limit(0);
// $menus = file_get_contents('menus.json');
// $menus = json_decode($menus, true);
// $html = [];
// foreach($menus as $mu){
//     $content = fetchContent($mu[1]);
//     $html[] = [$mu[0],$mu[1],$content];
// }
// file_put_contents('contents.json', json_encode($html, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES));

// //json to html
// $contents = file_get_contents('contents.json');
// $contents = json_decode($contents, true);
// $html = '';
// foreach($contents as $cont){
//     $contX = str_replace("\r\n\t", '<br>', trim($cont[2]));
//     $html .= "<h2>{$cont[0]}</h2><div>{$contX}<br></div>";
// }
// // echo $html;
// file_put_contents('contents.html', $html);

// json to menu
$menus = file_get_contents('menus.json');
$menus = json_decode($menus, true);
$html = '';
foreach($menus as $me){
    $html .= "<a href='{$me[1]}'>{$me[0]}</a><br>";
}
file_put_contents('menus.html',$html);


